<script lang="ts" setup>
import { useTheme } from "@@/composables/useTheme"
import { getCssVar } from "@@/utils/css"
import * as echarts from "echarts"

interface Props {
  title: string
  chartType: "line" | "bar" | "pie"
  data: any
  loading?: boolean
  height?: string
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  height: "400px"
})

const chartRef = ref<HTMLDivElement>()
let chartInstance: echarts.ECharts | null = null

// 主题变量，仅用于触发配置重算（不再使用 ECharts 内置主题切换）
const { activeThemeName } = useTheme()

// 折线图配置
function getLineChartOption(data: any): echarts.EChartsOption {
  return {
    // 让图表背景透明，避免 ECharts dark 主题默认背景色 (#100C2A/#100C28)
    backgroundColor: "transparent",
    tooltip: {
      trigger: "axis",
      backgroundColor: getCssVar("--el-bg-color") || "#ffffff",
      borderColor: getCssVar("--el-border-color-lighter") || "#e5e7eb",
      borderWidth: 1,
      textStyle: {
        color: getCssVar("--el-text-color-regular") || "#374151"
      },
      formatter: (params: any) => {
        let result = `${params[0].axisValue}<br/>`
        params.forEach((param: any) => {
          result += `${param.marker}${param.seriesName}: ${param.value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ["发布内容", "生成内容"],
      right: "right",
      textStyle: {
        color: getCssVar("--el-text-color-secondary") || "#6b7280"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: data.dates || [],
      axisLine: {
        lineStyle: {
          color: getCssVar("--el-border-color-lighter") || "#e5e7eb"
        }
      },
      axisLabel: {
        color: getCssVar("--el-text-color-secondary") || "#6b7280"
      }
    },
    yAxis: {
      type: "value",
      axisLine: {
        lineStyle: {
          color: getCssVar("--el-border-color-lighter") || "#e5e7eb"
        }
      },
      axisLabel: {
        color: getCssVar("--el-text-color-secondary") || "#6b7280"
      },
      splitLine: {
        lineStyle: {
          color: getCssVar("--el-border-color-extra-light") || "#f3f4f6",
          type: "dashed"
        }
      }
    },
    series: [
      {
        name: "发布内容",
        type: "line",
        smooth: true,
        data: data.published || [],
        lineStyle: {
          color: "#10b981",
          width: 3
        },
        itemStyle: {
          color: "#10b981"
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(16, 185, 129, 0.3)" },
              { offset: 1, color: "rgba(16, 185, 129, 0.05)" }
            ]
          }
        }
      },
      {
        name: "生成内容",
        type: "line",
        smooth: true,
        data: data.generated || [],
        lineStyle: {
          color: "#8b5cf6",
          width: 3
        },
        itemStyle: {
          color: "#8b5cf6"
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(139, 92, 246, 0.3)" },
              { offset: 1, color: "rgba(139, 92, 246, 0.05)" }
            ]
          }
        }
      }
    ]
  }
}

// 柱状图配置
function getBarChartOption(data: any): echarts.EChartsOption {
  return {
    backgroundColor: "transparent",
    tooltip: {
      trigger: "axis",
      backgroundColor: getCssVar("--el-bg-color") || "#ffffff",
      borderColor: getCssVar("--el-border-color-lighter") || "#e5e7eb",
      borderWidth: 1,
      textStyle: {
        color: getCssVar("--el-text-color-regular") || "#374151"
      },
      formatter: (params: any) => {
        const param = params[0]
        return `${param.name}<br/>${param.marker}avgDaily: ${param.value}`
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: data.versions || [],
      axisLine: {
        lineStyle: {
          color: getCssVar("--el-border-color-lighter") || "#e5e7eb"
        }
      },
      axisLabel: {
        color: getCssVar("--el-text-color-secondary") || "#6b7280"
      }
    },
    yAxis: {
      type: "value",
      axisLine: {
        lineStyle: {
          color: getCssVar("--el-border-color-lighter") || "#e5e7eb"
        }
      },
      axisLabel: {
        color: getCssVar("--el-text-color-secondary") || "#6b7280"
      },
      splitLine: {
        lineStyle: {
          color: getCssVar("--el-border-color-extra-light") || "#f3f4f6",
          type: "dashed"
        }
      }
    },
    series: [
      {
        type: "bar",
        data: data.values?.map((value: number, index: number) => ({
          value,
          itemStyle: {
            color: index === 0 ? (getCssVar("--el-text-color-placeholder") || "#9ca3af") : (getCssVar("--el-color-primary") || "#8b5cf6")
          }
        })) || [],
        barWidth: "60%",
        label: {
          show: true,
          position: "top",
          color: getCssVar("--el-text-color-regular") || "#374151",
          fontSize: 12
        }
      }
    ]
  }
}

// 饼图配置
function getPieChartOption(data: any): echarts.EChartsOption {
  const total = data?.reduce((sum: number, item: any) => sum + item.value, 0) || 0

  return {
    backgroundColor: "transparent",
    tooltip: {
      trigger: "item",
      backgroundColor: getCssVar("--el-bg-color") || "#ffffff",
      borderColor: getCssVar("--el-border-color-lighter") || "#e5e7eb",
      borderWidth: 1,
      textStyle: {
        color: getCssVar("--el-text-color-regular") || "#374151"
      },
      formatter: (params: any) => {
        const percentage = ((params.value / total) * 100).toFixed(1)
        return `${params.name}<br/>${params.marker}${params.value} (${percentage}%)`
      }
    },
    legend: {
      orient: "vertical",
      right: "10%",
      top: "center",
      textStyle: {
        color: getCssVar("--el-text-color-secondary") || "#6b7280"
      },
      formatter: (name: string) => {
        const item = data?.find((d: any) => d.name === name)
        return `${name}: ${item?.value || 0}`
      }
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        center: ["35%", "50%"],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: "inside",
          formatter: (params: any) => {
            // 只在Pro版切片上显示比例标签
            if (params.name === "Pro版") {
              return `1 : ${params.value}`
            }
            return ""
          },
          color: getCssVar("--el-color-white") || "#ffffff",
          fontSize: 12,
          fontWeight: 500
        },
        labelLine: {
          show: false
        },

        data: data?.map((item: any) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: item.color
          }
        })) || []
      }
    ]
  }
}

// 获取图表配置
function getChartOption(): echarts.EChartsOption {
  switch (props.chartType) {
    case "line":
      return getLineChartOption(props.data)
    case "bar":
      return getBarChartOption(props.data)
    case "pie":
      return getPieChartOption(props.data)
    default:
      return {}
  }
}

// 初始化图表
function initChart() {
  if (!chartRef.value) return

  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表
function updateChart() {
  if (!chartInstance) return

  const option = getChartOption()
  chartInstance.setOption(option, true)
}

// 调整图表大小
function resizeChart() {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 监听数据变化
watch(
  () => props.data,
  () => {
    updateChart()
  },
  { deep: true }
)

// 监听loading状态
watch(
  () => props.loading,
  (loading: boolean) => {
    if (chartInstance) {
      if (loading) {
        chartInstance.showLoading("default", {
          text: "加载中...",
          color: getCssVar("--el-color-primary") || "#8b5cf6",
          textColor: getCssVar("--el-text-color-secondary") || "#6b7280",
          maskColor: getCssVar("--el-overlay-color") || "rgba(255, 255, 255, 0.8)"
        })
      } else {
        chartInstance.hideLoading()
      }
    }
  }
)

// 处理echarts滚动警告问题
function patchWheelPassive() {
  const originalAddEventListener = EventTarget.prototype.addEventListener
  EventTarget.prototype.addEventListener = function (type, listener, options) {
    if (type === "mousewheel" || type === "wheel") {
      if (typeof options === "object") {
        options.passive = options.passive !== false // 保留原有 passive 配置
      } else {
        options = { passive: true } // 处理字符串或未定义的情况（如 addEventListener('wheel', fn, true)）
      }
    }
    return originalAddEventListener.call(this, type, listener, options)
  }

  // 提供恢复方法
  return () => {
    EventTarget.prototype.addEventListener = originalAddEventListener
  }
}

// 使用示例
// const restore = patchWheelPassive()
// 初始化 ECharts...
// 恢复原始方法（如果需要）
// restore();

// 组件挂载
onMounted(() => {
  patchWheelPassive()
  initChart()
  window.addEventListener("resize", resizeChart, { passive: true })
})

// 组件卸载
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener("resize", resizeChart)
})

// 监听主题切换：重新设置配置（颜色等来自 CSS 变量）
watch(
  () => activeThemeName.value,
  () => {
    updateChart()
  }
)
</script>

<template>
  <div class="chart-container">
    <CardHeader :title="title" />
    <div class="chart-content">
      <div
        ref="chartRef"
        class="chart"
        :style="{ height, touchAction: 'auto' }"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chart-container {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;

  &:hover {
    box-shadow: var(--el-box-shadow-lighter);
    border-color: var(--el-border-color);
  }

  .chart-content {
    flex: 1;
    padding: 20px;
    overflow: hidden;
    /* 关键修复：防止 chart 容器在 Grid 中强制撑开列宽 */
    min-width: 0;

    .chart {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
